package tto.gio.next;


import java.io.BufferedWriter;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;

import support.Variables;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
import android.util.Log;




public class Reporter {
	private DBMS mDB;
	
	protected Reporter(Context context)
	{
		this.mContext = context;
		mDB = DBMS.GetInstance(mContext);
	}
	public boolean ReportEvent()
	{		
		return true;
	}
	public static Reporter GetReporter(Context context)
	{
		if(mrp == null)
		{
			mrp = new Reporter(context);
		}
		return mrp;
	}
	
////////////////////////Socket Programming
	 public void report(StringBuilder sb)
	 {
		 if(Variables.isOTA)	
		 {
			reporter  = new Thread(SendReport,"repoter");
		 	
		 }
		 else //db version
		 {
			 reporter = new Thread(SaveReportToDB, "DBReport"); 
		 }
		 if(mrp.msg != null)
			 mrp.msg.setLength(0);
		 mrp.msg = sb;
		 reporter.start();
	 }
	 
	 public void onClose()
	 {
		 //if(Variables.isDBDebug)
		 //	 mDB.PrintDB();
		 mDB.Close();
		 mDB = null;
	 }
	 
	public Runnable SendReport = new Runnable(){
		 public void run(){
			 int  port = 17777;
			 String host = "147.46.240.145";
			 try{
				 Socket socket = new Socket(host,port);
				 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
			     out.println(msg);
				 System.out.println("-------------------------------------------------------");
				 out.close();
			 }catch(Exception ee)
			 {
				String str = ee.toString();//GetLocationMgr();
				System.out.print(str);
			 } 
			 
		 }
	 };
	 public Runnable SaveReportToDB = new Runnable(){
		 public void run(){
			 
			 try{
				 mDB.Insert(msg);
			 }catch(Exception ee)
			 {
				ee.printStackTrace();
			 } 
			 
		 }
	 };
	 private Thread reporter;
	 protected static Reporter mrp;
	 protected StringBuilder msg;
	 
//////////////////////end of socket programming
//////////////////////HTTP programming
	public void RequestCellInfo(Context context, int cid, int nac)
	 {		 
		 mContext = context;
		 mCid = cid;
		 mNac = nac;
		 mCellInfoRequester = new Thread(SendCellInfoRequest,"SendCellInfoRequest");
		 mCellInfoRequester.run();
	 }

	public Runnable SendCellInfoRequest = new Runnable() {
		@SuppressLint("NewApi")
		public void run() {
			try {
				StrictMode.ThreadPolicy thp = 
					new  StrictMode.ThreadPolicy.Builder().detectNetwork().permitAll().build();
				
				StrictMode.setThreadPolicy(thp);
				
				GetCellInfo(mContext, mCid, mNac);
				
				
			} catch (Exception ee) {
				ee.printStackTrace();
			}
		}

		protected void WriteData(OutputStream out, int cellID, int lac)
				throws IOException {

			
			//cellID = 5496;       
			//lac = 6037;
			
			DataOutputStream dataOutputStream = new DataOutputStream(out);
			dataOutputStream.writeShort(21);
			dataOutputStream.writeLong(0);
			dataOutputStream.writeUTF("en");
			dataOutputStream.writeUTF("Android");
			dataOutputStream.writeUTF("1.0");
			dataOutputStream.writeUTF("Web");
			dataOutputStream.writeByte(27);
			dataOutputStream.writeInt(0);
			dataOutputStream.writeInt(0);
			dataOutputStream.writeInt(3);
			dataOutputStream.writeUTF("");

			dataOutputStream.writeInt(cellID);
			dataOutputStream.writeInt(lac);

			dataOutputStream.writeInt(0);
			dataOutputStream.writeInt(0);
			dataOutputStream.writeInt(0);
			dataOutputStream.writeInt(0);
			
			//Log.d(TAG,dataOutputStream.toString());

			dataOutputStream.flush();
		}

		protected void GetCellInfo(Context context, int cellID, int lac)
				throws Exception {
			String urlString = "http://www.google.com/glm/mmap";

			// ---open a connection to Google Maps API---
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.connect();

			// ---write some custom data to Google Maps API---
			OutputStream outputStream = httpConn.getOutputStream();
			WriteData(outputStream, cellID, lac);

			// ---get the response---
			InputStream inputStream = httpConn.getInputStream();
			DataInputStream dataInputStream = new DataInputStream(inputStream);

			// ---interpret the response obtained---
			dataInputStream.readShort();
			dataInputStream.readByte();
			int code = dataInputStream.readInt();
			double cellLat,cellLon;
			if (code == 0) {
				cellLat = (double) dataInputStream.readInt() / 1000000D;
				cellLon = (double) dataInputStream.readInt() / 1000000D;
				dataInputStream.readInt();
				dataInputStream.readInt();
				dataInputStream.readUTF();
			}
			else
			{
				cellLat = -1;
				cellLon = -1;
			}
			Intent intent = new Intent();
			intent.setAction(Monitor.CELLTOWER_INTENT);
			intent.putExtra("cellLat", cellLat);
			intent.putExtra("cellLon", cellLon);
			
			
			Log.d(TAG, "Cell info : "+cellLat+ ", "+ cellLon);
			context.sendBroadcast(intent);

				
		}
	};
	

	
	private Thread mCellInfoRequester;
	protected Context mContext;
	protected int mCid;
	protected int mNac;
	private final String TAG="tto.gio.next";

//////////////////////end of HTTP programming
}
